#include "cresourcebundle.h"

/**
 * CResourceBundle - constructor, opens file and saves messages into map
 * @param path cesta k souboru
 */
CResourceBundle::CResourceBundle(string path) {
  loadMap(path);
}
//---------------------------------------------------------------------------

/**
 * ~CResourceBundle - destructor, deletes map if not empty
 */
CResourceBundle::~CResourceBundle() {
  if (messages.size()) freeMap();
}
//---------------------------------------------------------------------------

/**
 * getMessage - gets message from map
 * @param key
 * @return message assigned to key
 */
string CResourceBundle::getMessage(string key) {
  map<string, string>::iterator it = messages.find(key);
  if (it != messages.end()) return (*it).second;
  else throw CItemNotExistException(getClassName(), "getMessage");
}
//---------------------------------------------------------------------------

/**
 * freeMap - deletes map
 */
void CResourceBundle::freeMap() {
  messages.erase(messages.begin(), messages.end());
}
//---------------------------------------------------------------------------

/**
 * loadMap - opens file and saves messages into map
 * @param path
 */
void CResourceBundle::loadMap(string path) {

  // If map is not empty, delete it
  if (messages.size()) freeMap();

  // Open file
  ifstream file(path.c_str(), ios_base::in);

  // If file is not open, throw exception
  if (!file.is_open()) throw CFileNotExistException(getClassName(), "loadMap");

  // Read file and save messages into map
  string line;
  vector<string> tmp;
  while (!file.eof()) {
    getline(file, line);
    line = CStringUtils::removeMultipleSubstr(line, " ");
    if (line == "" || line == " ") continue;
    tmp = CStringUtils::explode("\"", line);
    messages[CStringUtils::removeSpaces(tmp[0])] = tmp[1];
  }

  // Close file
  file.close();
}
//---------------------------------------------------------------------------
